Grokking Tree Coding Patterns for Interviews
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Course Overview
Introduction to Tree
Types of Tree
BST Traversal Techniques
BST Operations
Introduction to Level Order Traversal Pattern
Reverse Level Order Traversal (easy)
Solution: Reverse Level Order Traversal
Find Largest Value in Each Tree Row (medium)
Solution: Find Largest Value in Each Tree Row
Maximum Width of Binary Tree (medium)
Solution: Maximum Width of Binary Tree
Maximum Level Sum of a Binary Tree (medium)
Solution: Maximum Level Sum of a Binary Tree
Zigzag Traversal (medium)
Solution: Zigzag Traversal
Even Odd Tree (medium)
Solution: Even Odd Tree
N-ary Tree Level Order Traversal (hard)
Solution: N-ary Tree Level Order Traversal
Introduction to Tree Depth Pattern
Maximum Depth (or Height) of Binary Tree (easy)
Solution: Maximum Depth (or Height) of Binary Tree
Minimum Depth of a Binary Tree (easy)
Solution: Minimum Depth of a Binary Tree
Balanced Binary Tree (easy)
Solution: Balanced Binary Tree
Tree Diameter (easy)
Solution: Tree Diameter
Maximum Depth of N-ary Tree (easy)
Solution: Maximum Depth of N-ary Tree
Find maximum depth of subtree (medium)
Solution: Find maximum depth of subtree
Introduction to Root to Leaf Path Pattern
Binary Tree Paths (easy)
Solution: Binary Tree Paths
Sum of Root To Leaf Binary Numbers (easy)
Solution: Sum of Root To Leaf Binary Numbers
Insufficient Nodes in Root to Leaf Paths (medium)
Solution: Insufficient Nodes in Root to Leaf Paths
Smallest String Starting From Leaf (medium)
Solution: Smallest String Starting From Leaf
Pseudo-Palindromic Paths in a Binary Tree (medium)
Solution: Pseudo-Palindromic Paths in a Binary Tree
All Paths for a Sum (medium)
Solution: All Paths for a Sum
Sum of Path Numbers (medium)
Solution: Sum of Path Numbers
Path With Given Sequence (medium)
Solution: Path With Given Sequence
Count Paths for a Sum (medium)
Solution: Count Paths for a Sum
Introduction to Leaf Processing Pattern
Sum of Left Leaves (easy)
Solution: Sum of Left Leaves
Leaf-Similar Trees (easy)
Solution: Leaf-Similar Trees
Check if all leaves are at same level (medium)
Solution: Check if all leaves are at same level
Delete Leaves With a Given Value (medium)
Solution: Delete Leaves With a Given Value
Deepest Leaves Sum (medium)
Solution: Deepest Leaves Sum
Introduction to Tree View Pattern
Right View of a Binary Tree (medium)
Solution: Right View of a Binary Tree
Top View Of the Binary Tree (medium)
Solution: Top View Of the Binary Tree
Bottom View Of the Binary Tree (medium)
Solution: Bottom View Of the Binary Tree
Boundary of Binary Tree (medium)
Solution: Boundary of Binary Tree
Introduction to Comparison of Two Trees Pattern
Symmetric Tree (easy)
Solution: Symmetric Tree
Mirror Image Trees (medium)
Solution: Mirror Image Trees
Subtree of Another Tree (easy)
Solution: Subtree of Another Tree
Isomorphic Trees (medium)
Solution: Isomorphic Trees
Introduction to Serialize and Deserialize Tree Pattern
Serialize and Deserialize BST (medium)
Solution: Serialize and Deserialize BST
Verify Preorder Serialization of a Binary Tree (medium)
Solution: Verify Preorder Serialization of a Binary Tree
Create Binary Tree From Descriptions (medium)
Solution: Create Binary Tree From Descriptions
Serialize and Deserialize N-ary Tree (hard)
Solution: Serialize and Deserialize N-ary Tree
Solution: Binary Tree Path Sum

Problem Statement

Given a root of the binary tree and an integer S, return true if the tree has a path from root-to-leaf such that the sum of all the node values of that path equals S. Otherwise, return false.

Examples

Example 1:

  • Input: root = [1, 2, 3, 4, 5, 6, 7], S = 10
Image
  • Expected Output: true
  • Justification: The tree has 1 -> 3 -> 6 root-to-leaf path having sum equal to 10.

Example 2:

  • Input: root = [12, 7, 1, 9, null, 10, 5], S = 23
Image
  • Expected Output: true
  • Justification: The tree has 12 -> 1 -> 10 root-to-leaf path having sum equal to 23.

Example 3:

  • Input: root = [12, 7, 1, 9, null, 10, 5], S = 16
Image
  • Expected Output: false
  • Justification: The tree doesn't have root-to-leaf path having sum equal to 16.

Constraints:

  • The number of nodes in the tree is in the range [0, 5000].
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000

Solution

The Binary Tree Path Sum problem involves determining whether there is a root-to-leaf path in a binary tree such that the sum of the node values along the path equals a given target sum. The algorithm traverses the tree recursively, adjusting the target sum at each step by subtracting the value of the current node. At each step, we pass the updated target sum to the recursive DFS call. If a leaf node is reached and its value matches the adjusted sum, a valid path has been found.

Step-by-Step Algorithm

  1. Check if the root is null:

    • If the root is null, return false because there is no path in an empty tree.
  2. Check if the current node is a leaf:

    • If the current node is a leaf, and its value matches the current sum (target sum minus the values encountered so far), return true, indicating that a valid path has been found.
  3. Traverse the left and right subtrees:

    • If the current node is not a leaf, adjust the sum by subtracting the value of the current node from the target sum.
    • Recursively check both the left and right children, passing the updated sum to both recursive calls.
  4. Return true if any recursive call returns true:

    • If any of the recursive calls (left or right subtree) returns true, return true to indicate that a valid path has been found.
    • Otherwise, return false if neither of the recursive calls finds a valid path.

Algorithm Walkthrough

Image
  1. Step 1 - Start at the root node (12):

    • The current node is 12.
    • The target sum is 23.
    • Check if the current node is null: No.
    • Check if the current node is a leaf: No (it has left and right children).
    • Subtract the current node's value from the target sum: 23 - 12 = 11.
    • Now recursively check both the left and right subtrees, with the new sum 11.
  2. Step 2 - Traverse the left subtree (Node 7):

    • The current node is 7.
    • The target sum is 11.
    • Check if the current node is null: No.
    • Check if the current node is a leaf: No (it has a left child).
    • Subtract the current node's value from the target sum: 11 - 7 = 4.
    • Now recursively check the left subtree with the new sum 4 (as the right child is null).
  3. Step 3 - Traverse the left subtree (Node 9):

    • The current node is 9.
    • The target sum is 4.
    • Check if the current node is null: No.
    • Check if the current node is a leaf: Yes (it has no left or right children).
    • Check if the current node's value matches the target sum: 9 != 4.
    • Since the values do not match, return false and backtrack to node 7.
  4. Step 4 - Traverse the right subtree of Node 12 (Node 1):

    • Backtrack to node 12 and now traverse its right subtree.
    • The current node is 1.
    • The target sum is 11 (from step 1).
    • Check if the current node is null: No.
    • Check if the current node is a leaf: No (it has left and right children).
    • Subtract the current node's value from the target sum: 11 - 1 = 10.
    • Now recursively check both the left and right subtrees with the new sum 10.
  5. Step 5 - Traverse the left subtree (Node 10):

    • The current node is 10.
    • The target sum is 10.
    • Check if the current node is null: No.
    • Check if the current node is a leaf: Yes (it has no left or right children).
    • Check if the current node's value matches the target sum: 10 == 10.
    • Since the values match, return true indicating that a valid path (12 → 1 → 10) has been found.
  6. Step 6 - Return final result:

    • Since we found a valid path in step 5, the algorithm returns true for the input tree and sum 23.

Final Output:

  • The tree has a path with a sum of 23: 12 → 1 → 10. Hence, the result is true.

Code

Java

. . . .

Complexity Analysis

Time Complexity

The time complexity of the above algorithm is , where ‘N’ is the total number of nodes in the tree. This is due to the fact that we traverse each node once.

Space Complexity

The space complexity of the above algorithm will be in the worst case. This space will be used to store the recursion stack. The worst case will happen when the given tree is a linked list (i.e., every node has only one child).

Binary Tree Path Sum (easy)
Count Good Nodes in Binary Tree (medium)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Final Output:

Code

Complexity Analysis

Time Complexity

Space Complexity